<?use pft\Prod\Product;
include 'common/autoload.php';
include 'module/link_product/function.php';
include_once('/var/www/html/new/d/class/abc/Syslog.class.php');
include_once("class/ProductInfo.php");//
if(!$_SESSION['memberID']){exit("<script>window.location='dlogin.html'</script>");}
$ac=$GLOBALS['_ac'];
$pw=$GLOBALS['_pw'];
$s = new SoapClient(null,array("location" => "http://localhost/open/openService/pft_insideMX.php","uri" => "www.16u.com?ac_16u=$ac|pw_16u=$pw|auth_16u=true"));
$pid=$_REQUEST["pid"];
$did=$_REQUEST["did"];
$pri=$_REQUEST["pri"];
$sPri=$_REQUEST["sPri"];
$lvl=$_REQUEST["lvl"];
$aids=$_REQUEST["aids"];
$sourceid=$_REQUEST["sourceid"];
$account = ($_SESSION['saccount'])? $_SESSION['saccount']:$_SESSION['account'];
$xml = $s->Dynamic_Price_And_Storage($account,$pid,date("Y-m-d"),1,0,0,$_REQUEST['sid']);
if($xml==105) $xml = $s->Dynamic_Price_And_Storage($account,$pid,date("Y-m-d"),2,0,0,$_REQUEST['sid']);
$object = simplexml_load_string($xml);
$fp=(string)$object->Rec->UUsprice;
$fp = $fp/100;
$dfp = $fp;
$evolute=$ssid=$inc_e=$del_e=$supid=$exist=$list=$has=$ch=$can=$temp=array();
if($did){
	
	$aid=explode(",",$aids);
	
	for($i=count($aid)-1;$i>=0;$i--){
		
		if(!$_pid){$_pid=$_SESSION['sid'];}
		$sel="select dprice from uu_priceset where aid=".($i==0?0:$aid[$i])." and tid=".$pid." and pid=".$_pid;
		$GLOBALS['le']->query($sel);
		$GLOBALS['le']->fetch_assoc();
		$fp+=$GLOBALS['le']->f("dprice")/100;
		$_pid=$aid[$i];
	}
	
    $fp = $dfp; 
	if($sourceid){
		//原已有权限者
		$sel="select fid from pft_p_apply_evolute where sid=".$_SESSION['sid']." and pid=".$pid;
		$GLOBALS['le']->query($sel);
		while($row=$GLOBALS['le']->fetch_assoc()){
			$has[]=$row['fid'];
		}
		//原已有配置者
		$sel="select pid from uu_priceset where aid=".$_SESSION['sid']." and tid=".$pid." and pid in (".implode(",",$did).")";
		$GLOBALS['le']->query($sel);
		while($row=$GLOBALS['le']->fetch_assoc()){
			$exist[]=$row['pid'];
		}
	}
	else{
			
		$sel="select fid,pids from pft_product_sale_list where aid=".$_SESSION['sid']." and fid in (".implode(",",$did).")";
		$GLOBALS['le']->query($sel);
		while($row=$GLOBALS['le']->fetch_assoc()){
			if($row['pids']=="A"){$has[]=$row['fid'];}
			else{
				$t=array_flip(explode(",",$row['pids']));
				if(isset($t[$pid])){$has[]=$row['fid'];}
				$can[$row['fid']]=$t;
			}
		}
		$sel="select pid from uu_priceset where aid=0 and tid=".$pid." and pid in (".implode(",",$did).")";
		$GLOBALS['le']->query($sel);
		while($row=$GLOBALS['le']->fetch_assoc()){
			$exist[]=$row['pid'];
		}
	}
	
	if(in_array("",$pri) || in_array("禁售",$pri)){
		$sel="select id,sid,fid from pft_p_apply_evolute where pid=".$pid." and lvl>=".(int)$lvl."+2 and status=0 order by lvl ASC";
        // echo $sel;
		$GLOBALS['le']->query($sel);
		while($row=$GLOBALS['le']->fetch_assoc()){
			if(in_array($row['sid'],$did)){
				$evolute[$row['sid']][]=$row['id'];
				$supid[]=$row['fid'];
				$ssid[$row['fid']]=$row['sid'];
			}
			elseif(in_array($row['sid'],$supid)){
				$evolute[$ssid[$row['sid']]][]=$row['id'];
			}
		}
	}
}
// print_r($did);
// print_r($pri);
// print_r($fp);
foreach($did as $d){
	if($pri[$d]=="" || $pri[$d]=="禁售"){
		if(in_array($d,$has)){
			$del_e[]=$d;
			if(!$sourceid){
				if(isset($can[$d])){unset($can[$d][$pid]);}
				else{
					if(!$list){
						$sel="select id from uu_products where p_status in (0,3) and apply_did=".$_SESSION['sid'];
						$GLOBALS['le']->query($sel);
						while($row=$GLOBALS['le']->fetch_assoc()){
							$list[]=$row['id'];
						}
						$list=array_flip($list);
					}
					$can[$d]=$list;
				}
				$ch[$d]=$can[$d];
			}
		}
	}
	else{
		$p=$pri[$d]-$fp;
		if(filter_var($p, FILTER_VALIDATE_FLOAT)===false){
			exit("<script>alert('设定的价格存在非法字符!');</script>");
		}
		if($p<0){
			$sel="select dname from pft_member where id =".$d." limit 1";
			$GLOBALS['le']->query($sel);
			$GLOBALS['le']->fetch_assoc();
			exit("<script>alert('给".$GLOBALS['le']->f("dname")."配置的价格不正确');</script>");
		}
		if(in_array($d,$exist)){
			$temp[$d]=$p;
		}
		else{
			$str.="(".$d.",".$pid.",".($p*100).",".($sourceid?$_SESSION['sid']:0)."),";
		}
		if(!in_array($d,$has)){
			if($sourceid){
				$str2.="(".$d.",".$pid.",".$_SESSION['sid'].",".$sourceid.",".($lvl+1).",'".$aids.",".$_SESSION['sid']."',now()),";
			}
			else{
				$can[$d][$pid]=count($can[$d])+1;
				$ch[$d]=$can[$d];
			}
		}
		$inc_e[]=$d;
	}
}
//if(isset($pri[4]) || isset($pri[108])){//同步
//	$sel="select pft_rflex_id from uu_jq_ticket where pid=".$pid." limit 1";
//	$GLOBALS['le']->query($sel);
//	$GLOBALS['le']->fetch_assoc();
//	$rid=$GLOBALS['le']->f("pft_rflex_id");
//	if($rid){
//		if(is_numeric($pri[4]) || is_numeric($pri[108])){
//			$opri=is_numeric($pri[4])?$pri[4]:$pri[108];
//			$p=$opri-$fp;
//			$pro = new Product($GLOBALS['le']);
//			$ret = json_decode($pro->SyncTicketState(1, $pid),true);
//			if($ret['status']!="ok"){
//				exit("<script>alert('".$pid.$ret['msg']."');</script>");
//			}
//			$price = new Price(-1);
//			$ret = $price->PriceSync($pid, $rid, ($p*100));
//			if($ret!=100){
//				exit("<script>alert('".$pid."-".$rid."-".$p."失败".$ret."');</script>");
//			}
//		}
//		else{
//			$pro = new Product($GLOBALS['le']);
//			$ret = json_decode($pro->SyncTicketState(2, $pid),true);
//			if($ret['status']!="ok"){
//				exit("<script>alert('".$pid.$ret['msg']."');</script>");
//			}
//		}
//	}
//}

// exit;
foreach($del_e as $v){
/*	switch((int)$lvl){
		case 0:$aid="or aids='".$_SESSION['sid'].",".$v."'";break;//INSTR(aids,'".$_SESSION['sid'].",".$v."')
		case 1:$aid="or aids='".$sourceid.",".$_SESSION['sid'].",".$v."'";break;
		case 2:$aid="";break;
	}
	$upd="update pft_p_apply_evolute set status=1 where pid=".$pid." and ((sid=".$_SESSION['sid']." and fid=".$v.") ".$aid.")";//(LOCATE('".$v."', aids)=".(int)$lvl." )*/
	$upd="update pft_p_apply_evolute set status=1 where pid=".$pid." and ((sid=".$_SESSION['sid']." and fid=".$v.")".(isset($evolute[$v])?" or id in (".implode(",",$evolute[$v]).")":"").")";
    // echo $upd;
    // print_r($evolute);
	$GLOBALS['le']->query($upd);
	// abc777\Syslog::write_log($upd,'pft_p_apply_evolute');
}
foreach($inc_e as $d){
	$upd="update pft_p_apply_evolute set status=0 where status=1 and pid=".$pid." and sid=".$_SESSION['sid']." and fid=".$d;
	// echo $upd;
	$GLOBALS['le']->query($upd);
	// abc777\Syslog::write_log($upd,'pft_p_apply_evolute');
}
// if($_SESSION['debug']){
		// print_r($ch);
		// exit;
	// }
if($sourceid){
	if($str2){
		$ins="insert pft_p_apply_evolute (fid,pid,sid,sourceid,lvl,aids,rectime) values ".trim($str2,",");//echo $ins;
		// echo $ins;
		$GLOBALS['le']->query($ins);
		// abc777\Syslog::write_log($ins,'pft_p_apply_evolute');
	}
}
else{
	foreach($ch as $k=>$v){
		$upd="update pft_product_sale_list set pids='".implode(",",array_unique(array_diff(array_flip($v), array(null,'null','',' '))))."' where aid=".$_SESSION['sid']." and fid=".$k;//echo $upd;
		// echo $upd;
		echo $GLOBALS['le']->query($upd);
		$logStr = $_SESSION['sid'].'|'.$_SESSION['memberID'].'|adj|'.$upd;
		// abc777\Syslog::write_log($logStr,'pft_product_sale_list');
	}
}
// print_r($temp);
foreach($temp as $k=>$v){
	$upd="update uu_priceset set dprice=".($v*100)." where aid=".($sourceid?$_SESSION['sid']:0)." and pid=".$k." and tid=".$pid." limit 1";
    // echo $sourceid;
    // echo $upd;
	echo $GLOBALS['le']->query($upd);
	// abc777\Syslog::write_log($upd,'uu_priceset');
}
if($str){
	$ins="insert into uu_priceset (pid,tid,dprice,aid) values ".trim($str,",");//echo $ins;
	// echo $ins;
	$GLOBALS['le']->query($ins);
	// abc777\Syslog::write_log($ins,'uu_priceset');
}
$sel="select p_name from uu_products where id=".$pid." limit 1";
$GLOBALS['le']->query($sel);
$GLOBALS['le']->fetch_assoc();
$ins="insert pft_d_operation_rec set fid=".$_SESSION['memberID'].",sid=".$_SESSION['sid'].",daction='对".$GLOBALS['le']->f("p_name")."的分销价格进行配置',rectime=now()";
$GLOBALS['le']->query($ins);
// 有套票则上调套票价格
$package = getMainId($pid);
if(count($package)) {
	$ids = implode(',', $package);
	$pri_key = implode(',', array_keys($pri));
	// 找出套票供应商
	$sql="SELECT l.apply_did,l.attribute,t.pid FROM uu_land l LEFT JOIN uu_jq_ticket t ON t.landid=l.id WHERE l.apply_did IN ($pri_key) AND l.id IN ($ids)";
	$GLOBALS['le']->query($sql);
	$apy = array();
	while($row=$GLOBALS['le']->fetch_assoc()){
		$apy[]=$row;
	}

	// 如果配置有套票并且供应商存在配置项
	if(count($apy)){
		$upper = array();
		$proPri = new Price(-1);
		foreach($apy as $val){
			$att = json_decode($val['attribute'], true);
			foreach($att as $v){
				if($v['pid']==$pid){//找到子票
					// 本次增加的分销价是否供应商有在内
					if(empty($pri[$val['apply_did']])) $pri[$val['apply_did']] = 0;
					if(empty($sPri[$val['apply_did']])) $sPri[$val['apply_did']] = 0;
					$diff = $pri[$val['apply_did']]-$sPri[$val['apply_did']];
					if($diff <= 0) continue;
					$xml = $proPri->GetDynamicPrice('', 0, date('Y-m-d'),'',0,1,$val['pid']);
					$obj = (array)simplexml_load_string($xml);
					foreach($obj as $pv){
						$targetSpri = $pv->UUn_price + $diff * 100;
						$targetLpri = $pv->UUl_price + $diff * 100;
						Price::DynamicPriceStatic((string)$pv->UUpid, (string)$pv->UUstart_date, (string)$pv->UUend_date, $targetSpri, $targetLpri, (string)$pv->UUptype, (string)$pv->UUid, (string)$pv->UUmemo, (string)$pv->UUweekdays, $s, (string)$pv->UUstorage);
						$upper[] = (string)$pv->UUpid;
					}
				}
			}
		}
		if(count($upper)){// 发送通知给套票供应商
			include_once 'class/notice.class.php';
			include_once 'class/MemberAccount.class.php';
			$notice = new pft\notice();
			$pids = implode(',',$upper).','.$pid;
			$sql="SELECT p_name,apply_did,id FROM uu_products WHERE id IN ($pids) AND p_status<6";
			$GLOBALS['le']->query($sql);
			$pinfo = array();
			while($row=$GLOBALS['le']->fetch_assoc()){
				$pinfo[$row['id']]=$row;
			}
			// print_r($pinfo);
			$exclude = array();
			foreach($pinfo as $k => $v){
				if($k==$pid) continue;
				$msg = "您的套票产品【{$v['p_name']}】由于子票【{$pinfo[$pid]['p_name']}】分销价格上调，系统自动上调套票价格，如果不想调整，请自行设置";
				$debug = <<<h
				AddNotice('套票价格上调', $msg, 1, 9999, 1, 0, '', '',
					\pft\Member\MemberAccount(le, {$v['apply_did']},),
					{$v['apply_did']}
				);
h;
				// echo $debug;
				$notice->AddNotice('套票价格上调', $msg, 1, 9999, 1, 0, '', '',
					new \pft\Member\MemberAccount($GLOBALS['le'], $v['apply_did'], $s),
					$v['apply_did']
				);
			}
		}

	}
}
echo "<script>alert('配置成功')</script>";
?>